package com.letoken.platform.repo.app.redis;


import com.letoken.platform.repo.utlis.RedisClient;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 注入redis相关类
 *
 * @author Lowen
 * @date 2022-12-06
 */
@Configuration
public class RedisConfig {

	@Value("${spring.redis.host}")
	private String host;

	@Value("${spring.redis.port}")
	private int port;

	@Value("${spring.redis.timeout}")
	private int timeout;

	/*@Value("${spring.redis.maxIdle}")
	private int maxIdle;

	@Value("${spring.redis.maxWaitMillis}")
	private long maxWaitMillis;*/

	@Value("${spring.redis.password}")
	private String password;


	/**
	 * 配置RedisTemplate的序列化方式
	 */
	@Bean
	public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(factory);
		// 指定key的序列化方式：string
		redisTemplate.setKeySerializer(RedisSerializer.string());
		// 指定value的序列化方式：json
		redisTemplate.setValueSerializer(RedisSerializer.json());
		return redisTemplate;
	}

	/**
	 * 配置Redis缓存注解的value序列化方式
	 */
	@Bean
	public RedisCacheConfiguration redisCacheConfiguration(){
		RedisCacheConfiguration configuration =
				RedisCacheConfiguration.defaultCacheConfig();
		configuration = configuration.serializeValuesWith(
				RedisSerializationContext.SerializationPair.fromSerializer(
						RedisSerializer.json()
				)
		);
		return configuration;
	}

	@Bean
	public JedisPool jedisPool() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		/*jedisPoolConfig.setMaxIdle(maxIdle);
		jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);*/
		return new JedisPool(jedisPoolConfig, host, port, timeout, password);
	}

	@Bean
	public RedisClient redisClient(JedisPool jedisPool) {
		return new RedisClient(jedisPool);
	}

	@Bean
	public RedissonClient getRedisson() {
		Config config = new Config();
		config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password);
		config.useSingleServer().setConnectionMinimumIdleSize(10);
		return Redisson.create(config);

	}
}
